package com.tianhao.export.util;

import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;

/**
 * @author tianhao.luo@hand-china.com
 * @version 1.0
 * @date 2022年02月16日 星期三 1:18 下午
 * @description
 * @since 1.0
 */
public class KnifeHttpServletResponseHelper {
    private HttpServletResponse httpServletResponse;

    public KnifeHttpServletResponseHelper(HttpServletResponse httpServletResponse) {
        this.httpServletResponse = httpServletResponse;
    }

    public KnifeHttpServletResponseHelper setContentType(MediaType mediaType) {
        httpServletResponse.setContentType(mediaType.toString());
        return this;
    }


    public KnifeHttpServletResponseHelper setCharacterEncoding(Charset charset) {
        httpServletResponse.setCharacterEncoding(charset.toString());
        return this;
    }

    public KnifeHttpServletResponseHelper setExportFileName(Charset charset, String fileName, String fileType) {
        try {
            httpServletResponse.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + URLEncoder.encode(fileName, charset.toString()) + "." + fileType);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return this;
    }

}
